package com.zhouzhou.fastjava.web;

import com.google.common.net.MediaType;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.tika.Tika;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 快速下载
 */
public abstract class WebUtils {

    public static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";

    private static final SimpleDateFormat SDF = new SimpleDateFormat("_yyyyMMddHHmmss");

    public static String getIP(HttpServletRequest request) {
        String ip = request.getHeader("X-REAL-IP");
        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("X-FORWARDED-FOR");
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static final Tika tika = new Tika();

    public static final void writeFileWithTimestamp(HttpServletRequest request, HttpServletResponse response, InputStream is, String filename) throws IOException {

        writeFile(request, response, is, getWithTimestampFilename(request, filename));
    }

    public static final void writeFile(HttpServletRequest request, HttpServletResponse response, InputStream is, String filename) throws IOException {

        String contentType = tika.detect(filename);
        if (StringUtils.isBlank(contentType)) {
            contentType = MediaType.OCTET_STREAM.toString();
        }
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment;filename=" + getEncodedFilename(request, filename));
        IOUtils.copy(is, response.getOutputStream());
    }

    public static final void writeExcel(HttpServletRequest request, HttpServletResponse response, Workbook book, String filename) throws IOException {

        if (!filename.toLowerCase().endsWith(".xlsx")) {
            filename = filename + ".xlsx";
        }
        response.setContentType(tika.detect(filename));
        response.setHeader("Content-Disposition", "attachment;filename=" + getEncodedFilename(request, filename));
        book.write(response.getOutputStream());
    }

    public static final void writeDoc(HttpServletRequest request, HttpServletResponse response, XWPFDocument doc, String filename) throws IOException {

        if (!filename.toLowerCase().endsWith(".docx")) {
            filename = filename + ".docx";
        }
        response.setContentType(tika.detect(filename));
        response.setHeader("Content-Disposition", "attachment;filename=" + getEncodedFilename(request, filename));
        doc.write(response.getOutputStream());
    }

    public static String getLowerUserAgent(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT");
        if (StringUtils.isBlank(userAgent)) {
            return StringUtils.EMPTY;
        }
        userAgent = userAgent.toLowerCase();
        return userAgent;
    }

    public static boolean isIE(HttpServletRequest request) {

        String userAgent = getLowerUserAgent(request);
        return userAgent.contains("msie") || userAgent.contains("rv:11.0") || userAgent.contains("edge");
    }

    public static boolean isFirefox(HttpServletRequest request) {

        String userAgent = getLowerUserAgent(request);
        return userAgent.contains("firefox");
    }

    public static boolean isChrome(HttpServletRequest request) {

        String userAgent = getLowerUserAgent(request);
        return userAgent.contains("chrome");
    }

    public static String getWithTimestampFilename(HttpServletRequest request, String filename) {

        String basename = FilenameUtils.getName(filename);
        String extension = FilenameUtils.getExtension(filename);
        return getEncodedFilename(request, basename) + SDF.format(new Date()) + "." + extension;
    }

    private static String getEncodedFilename(HttpServletRequest request, String filename) {

        try {
            if (isIE(request)) {
                return java.net.URLEncoder.encode(filename, "UTF8");
            } else {
                if (isChrome(request)) {
                    return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
                } else {
                    filename = filename.replace(" ", "_");
                    return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private WebUtils() {
    }



}